package com.dean.utils;

import com.dean.constants.DeanUiConstants;
import com.dean.entity.DataQueryEntity;
import com.dean.entity.DeanDbConnInfo;
import com.dean.entity.DeanImportInfo;
import com.dean.entity.SysDbConnInfo;
import com.opencsv.*;
import com.opencsv.exceptions.CsvValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName DeanCsvUtils
 * @Description csv 工具类
 * @Author dean
 * @Date 2021/10/3 10:03
 */
public class DeanCsvUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(DeanCsvUtils.class);

	private static final String BOM="\uFEFF";
	/**
	 * excel 提交数量统计
	 */
	private static int commitCounts = 0;

	/**
	 * 单个sheet 页的总数量
	 */
	private static int totalCounts = 0 ;


	public static void readCsv(String fileName, SysDbConnInfo connInfo, DeanImportInfo importInfo) throws IOException, CsvValidationException {
		String delimiter = importInfo.getDelimiter();
		CSVParser parser = new CSVParserBuilder().withSeparator(delimiter.charAt(0)).build();
		CSVReader csvReader =new CSVReaderBuilder(Files.newBufferedReader(new File(fileName).toPath(), StandardCharsets.UTF_8)).withCSVParser(parser).build();
		List<String> heads = Arrays.asList(importInfo.getFields());
		if(heads.size() == 0){
			String [] head = csvReader.readNext();
			// utf-8 bom 文本开始有特殊字符  处理掉
			if(head[0].substring(0,1).contains(BOM)){
				head[0]=head[0].substring(1);
			}
			importInfo.setFields(head);
			heads = Arrays.asList(head);
		}
		logger.debug("读取到csv表头:{}",heads);
		boolean remarkFlag = true;
		String remark = fileName;
		if(heads.contains(DeanUiConstants.REMARK) || heads.contains(DeanUiConstants.REMARK.toLowerCase())){
			remarkFlag = false;
			remark = null;
		}
		String exeSql = DeanSqlUtils.createInsertSql(importInfo.getTableName(),importInfo.getFields(),remarkFlag);
		String [] record;
		List<List<String>> records = new ArrayList<List<String>>(importInfo.getCommitNums());
		while ((record = csvReader.readNext()) != null){
			List<String> recordList = Arrays.asList(record);
			records.add(recordList);
			commitCounts++;
			if(commitCounts == importInfo.getCommitNums()) {
				DeanJdbcUtils.batchInsert(connInfo,exeSql, records, remark);
				totalCounts += commitCounts;
				commitCounts = 0;
				records.clear();
			}
		}
		if(commitCounts > 0){
			DeanJdbcUtils.batchInsert(connInfo,exeSql, records, remark);
			totalCounts+=commitCounts;
		}
	}


	/**
	 * 写csv文件 分割符默认为","
	 * @param dataQueryEntity
	 * @param fileName
	 */
	public static void  writeCsv(DataQueryEntity dataQueryEntity, String fileName){
		String delimiter = ",";
		writeCsv( dataQueryEntity,  fileName,  delimiter);
	}
	/**
	 * 写入csv文件
	 * @param fileName
	 * @param delimiter
	 * @throws FileNotFoundException
	 * @throws UnsupportedEncodingException
	 */
	public static void  writeCsv(DataQueryEntity dataQueryEntity, String fileName, String delimiter) {
		CSVWriter csvWriter = null;
		OutputStreamWriter outputStreamWriter=null;
		try {
			outputStreamWriter = new OutputStreamWriter(new FileOutputStream(fileName),"UTF-8");
			csvWriter = new CSVWriter(outputStreamWriter,delimiter.charAt(0),'"', '"', "\n");
			csvWriter.writeNext(dataQueryEntity.getHeader());
			for (String [] data : dataQueryEntity.getDatas()) {
				csvWriter.writeNext(data);
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("当前任务执行失败,失败原因:{}",e.getMessage(),e);
		} catch (FileNotFoundException e) {
			logger.error("当前任务执行失败,失败原因::{}",e.getMessage(),e);
		}finally {
			if(csvWriter!=null){
				try {
					csvWriter.close();
				} catch (IOException e) {
					logger.error("当前任务执行失败,失败原因::{}",e.getMessage(),e);
				}
			}
		}

	}
}
